package csce315.group10.androidapp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import com.dropbox.client2.DropboxAPI.DropboxFileInfo;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.exception.DropboxUnlinkedException;
import com.dropbox.client2.session.AccessTokenPair;

import csce315.group10.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class YearBookAppActivity extends Activity {
	
	/* private instance variables */
	public CustomApp appState;
	private final static String TAG = YearBookAppActivity.class.getCanonicalName();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        appState = ((CustomApp)getApplicationContext());
        
        /* Use files to build CustomApp 
         * need to do this before authentication to get dropbox authentication
         * info if exists*/
		Log.i(TAG, "Read AppState from file.");
        Serializer serial = new Persister();
    	/* take the file from the sd card and deserialize */
        File sdcardFile = new File("/sdcard/customappData.xml");
    	try {
    		CustomApp state_from_file = serial.read(CustomApp.class, sdcardFile);
			appState.set_contact_list(state_from_file.GetContacts());
			appState.set_event_list(state_from_file.GetEvents());
			appState.set_pot_story_list(state_from_file.GetPStories());
			appState.store_keys(state_from_file.get_dbkey(), state_from_file.get_dbsecret());
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.i(TAG, "XML Read from File: " + sdcardFile.getAbsolutePath());
		/* initialize dropbox session*/
		appState.initializeDropbox();
        /* authenticate dropbox session 
         * but first check if authentication has occured before
         * */
    	if(appState.get_dbkey() == "" && appState.get_dbsecret() == ""){
    		appState.get_dropbox().getSession().startAuthentication(YearBookAppActivity.this);
    	}else{
        	/* get files from dropbox server */
        	
        	FileOutputStream foStream;
        	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        	try {
        	   DropboxFileInfo info = appState.get_dropbox().getFile("/customappData.xml", null, outputStream, null);
        	   foStream = new FileOutputStream(sdcardFile);
        	   outputStream.writeTo(foStream);
        	   Log.i("DbLog", "File written to card from server " + info.getMetadata().rev);
        	   Log.i("DbLog", "The file's rev is: " + info.getMetadata().rev);
        	}catch (DropboxUnlinkedException e){
        		Log.e("DbLog", "access token not set");
        	}catch (DropboxException e) {
        	   Log.e("DbLog", "Something went wrong while downloading.");
        	} 
        	catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
            /* Use files to build CustomApp */
            /* take the file from the sd card and deserialize */
        	try {
        		CustomApp state_from_file = serial.read(CustomApp.class, sdcardFile);
    			appState.set_contact_list(state_from_file.GetContacts());
    			appState.set_event_list(state_from_file.GetEvents());
    			appState.set_pot_story_list(state_from_file.GetPStories());
    			appState.store_keys(state_from_file.get_dbkey(), state_from_file.get_dbsecret());
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		Log.i(TAG, "XML Read from File: " + sdcardFile.getAbsolutePath());
    	}
    }
    
    public void loginButtonHandler(View v){
    	/* get login info */
    	EditText username = (EditText) findViewById(R.id.Username_text);
    	String username_text = username.getText().toString();
    	EditText password = (EditText) findViewById(R.id.Password_text);
    	String password_text = password.getText().toString();
    	/* check if username is admin and password matches*/
    	if(username_text.equals("Admin")){
    		if(appState.get_admin().check_password(password_text)){
    			appState.set_current_user(appState.get_admin());
    			Intent intent = new Intent();
    	    	intent.setClass(this,MainMenu.class);
    	    	startActivity(intent);
    	    	finish();
    		}else{
    			Toast.makeText(this, "Username and Password combination incorrect" , Toast.LENGTH_LONG).show();
    		}
    	}
    	/* check if username exists */
    	for(int i = 0; i < appState.GetContacts().size(); i++){
    		/* check password */
    		if(username_text.equals(appState.GetContacts().get(i).get_name())){
    			if(appState.GetContacts().get(i).check_password(password_text)){
        			appState.set_current_user(appState.GetContacts().get(i));
        			Intent intent = new Intent();
        	    	intent.setClass(this,MainMenu.class);
        	    	
        	    	startActivity(intent);
        	    	finish();
        		}else{
        			Toast.makeText(this, "Username and Password combination incorrect" , Toast.LENGTH_LONG).show();
        		}
    			break;
    		}
    	}
    }

    protected void onResume() {
        super.onResume();

        if (appState.get_dropbox().getSession().authenticationSuccessful()) {
            try {
                // MANDATORY call to complete auth.
                // Sets the access token on the session
            	appState.get_dropbox().getSession().finishAuthentication();
            	/* get files from dropbox server */
            	File sdcardFile = new File("/sdcard/customappData.xml");
            	FileOutputStream foStream;
            	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            	try {
            	   DropboxFileInfo info = appState.get_dropbox().getFile("/customappData.xml", null, outputStream, null);
            	   foStream = new FileOutputStream(sdcardFile);
            	   outputStream.writeTo(foStream);
            	   Log.i("DbLog", "File written to card from server " );
            	   Log.i("DbLog", "The file's rev is: " + info.getMetadata().rev);
            	} catch (DropboxException e) {
            	   Log.e("DbLog", "Something went wrong while downloading.");
            	} catch (IOException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
                /* Use files to build CustomApp */
        		Log.i(TAG, "Read AppState from file.");
                Serializer serial = new Persister();
            	/* take the file from the sd card and deserialize */
            	try {
            		CustomApp state_from_file = serial.read(CustomApp.class, sdcardFile);
        			appState.set_contact_list(state_from_file.GetContacts());
        			appState.set_event_list(state_from_file.GetEvents());
        			appState.set_pot_story_list(state_from_file.GetPStories());
        			appState.store_keys(state_from_file.get_dbkey(), state_from_file.get_dbsecret());
        		} catch (Exception e) {
        			// There is the possibility of error for a number of reasons. Handle this appropriately in your code
        			e.printStackTrace();
        		}
        		Log.i(TAG, "XML Read from File: " + sdcardFile.getAbsolutePath());
                AccessTokenPair tokens = appState.get_dropbox().getSession().getAccessTokenPair();
                /* store tokens for later sessions*/
                appState.store_keys(tokens.key, tokens.secret);
            } catch (IllegalStateException e) {
                Log.i("DbAuthLog", "Error authenticating", e);
            }
        }
    }

}